package com.example.vote.listener;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.read.listener.ReadListener;
import com.alibaba.excel.util.ListUtils;
import com.example.vote.bean.TVote;
import com.example.vote.bean.UserVote;
import com.example.vote.service.TVoteServiceImpl;
import com.example.vote.service.UserVoteServiceImpl;
import org.springframework.util.StringUtils;

import java.util.List;


public class UserVoteLister implements ReadListener<UserVote> {
    /**
     * 每隔5条存储数据库，实际使用中可以100条，然后清理list ，方便内存回收
     */
    private static final int BATCH_COUNT = 100;
    /**
     * 缓存的数据
     */
    private List<UserVote> cachedDataList = ListUtils.newArrayListWithExpectedSize(BATCH_COUNT);
    private final UserVoteServiceImpl userVoteService;
    /**
     * 投票项目id
     */
    private final String itemId;

    public UserVoteLister(UserVoteServiceImpl userVoteService, String itemId) {
        this.userVoteService = userVoteService;
        this.itemId = itemId;
    }


    @Override
    public void invoke(UserVote userVote, AnalysisContext analysisContext) {
        if (!StringUtils.hasLength(userVote.getName())) {
            userVote.setName("未命名");
        }
        userVote.setItemId(itemId);
        cachedDataList.add(userVote);
        if (cachedDataList.size() >= BATCH_COUNT) {
            saveData();
            // 存储完成清理 list
            cachedDataList = ListUtils.newArrayListWithExpectedSize(BATCH_COUNT);
        }
    }


    /**
     * 所有数据解析完成了 都会来调用
     *
     * @param analysisContext
     */
    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {
        saveData();
    }

    private void saveData() {

        userVoteService.saveBatch(cachedDataList);
    }
}
